####################################################
# Allnetworkvariables.R
#
# This function computes all the network variables considered in Ductor, L., Fafchamps, M., Goyal S. and M. van der Leij. Social #Networks and Research Output. The Review of Economics and Statistics.
# 
#   Note: this program is time consuming (more than 3 weeks in a standard PC)         
#                
######################################################


#Obtaining the full sample of all authors (do only once)#

library(igraph)
source("netprodndnp.R")
source("netprod2ndnp.R")
source("getcoauthnetwk.R")
source("analyzenetw.R")

data<-read.csv("networkdatac.csv",header=TRUE)
dataqnt<-read.csv("qnt_fullsample.csv",header=TRUE)

# endyears and length to compute networks
ks <- 1:15

for (k in ks) {

  endyears <- (1970+k-1):1999

  for (endyear in endyears) {

    startyear <- endyear - k+1

    #COMPUTING COAUTHORS' PRODUCTIVITY AND DEGREE
    y <- subset(data,year>=startyear & year<=endyear)
    g <- getnetwork(startyear,endyear, data, y)

    y$auth3[is.na(y$auth3)]<--2  ### Replacing missing author by a number, -2
    y$auth2[is.na(y$auth2)]<--1  ### Replacing missing author by a number, -1

    V(g)$deg <- degree(g)
    V(g)[deg>0]$netprod <- sapply(V(g)[deg>0],netprod,g,y)

    V(g)$auth<-V(g)

    #COMPUTING COAUTHORS' COAUTHORS PRODUCTIVITY
    
    V(g)[deg>0]$netprod2<-sapply(V(g)[deg>0],netprod2,g,y)

    #COMPUTING THE DEGREE OF ORDER 2 
    V(g)$deg2<- neighborhood.size(g, 2) - V(g)$deg - 1

    #COMPUTING THE CENTRALITY VARIABLES
    gc<-get.giant.component(g)
    V(gc)$deg<-degree(gc)
    V(gc)$bet<-betweenness(gc)
    V(gc)$cl<-closeness(gc, normalized=TRUE)
    V(gc)$ev<-evcent(gc)$vector

    #COMPUTING THE TOP COAUTHORS DUMMY VARIABLE
    if (endyear >= 1970) {
      qnt1<-subset(dataqnt,qnt==1 & year==endyear,auth)
      qnt1v<-qnt1$auth
      neiq1v<-V(g)[nei(qnt1v)]
      V(g)[neiq1v]$neiq1fs<-1
    }
    else {
      V(g)$neiq1fs <- NA }

    d<-data.frame(V(g)$auth,V(g)$deg,V(g)$deg2,V(g)$netprod,V(g)$netprod2,
                     V(g)$neiq1fs)
    d2<-data.frame(V(gc)$auth,V(gc)$deg,V(gc)$bet,V(gc)$cl,V(gc)$ev)

    write.csv(d,file=paste("network", endyear, "_", k, "y.csv", sep=""),na=".")
    write.csv(d2,file=paste("networkgc", endyear, "_", k, "y.csv", sep=""),na=".")
  }
}